﻿/*
 *  创建人： LYC
 *  首页的一些功能：包括 列表页、左侧导航、筛选、权限导航绑定  Ef调用ado
 * 
 *  修改人：Wubinner
 *  修改时间：2017-9-15
 *  修改内容： 发布房源、委托找房
 */
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

using Partner.MVC.Model;
using Partner.MVC.Models;
using Newtonsoft.Json;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Net.Http;
using System.Text;

namespace Partner.MVC.Controllers
{
    public class PartnerController : Controller
    {
        // 实例化上下文集合
        GuyEntities db = new GuyEntities();

        #region 伙办首页 办公 公寓 商铺 地图找房 办公服务 个人中心
        /// <summary>
        ///  伙办首页
        /// </summary>
        /// <returns>State 指定账户是否操作注销</returns>
        public ActionResult PartnerIndex()
        {
            return View();
        }

        /// <summary>
        ///  伙办办公
        /// </summary>
        /// <returns></returns>
        public ActionResult PartnerWork()
        {
            return View();
        }
        /// <summary>
        ///  伙办公寓
        /// </summary>
        /// <returns></returns>
        public ActionResult PartnerApartment()
        {
            return View();
        }
        /// <summary>
        ///  伙办商铺
        /// </summary>
        /// <returns></returns>
        public ActionResult PartnerShop()
        {
            return View();
        }
        /// <summary>
        ///  判断收藏的房源在列表中高亮显示
        /// </summary>
        /// <returns></returns>
        public string coll(string htype, string cityname, string price, string mjadd, string zxadd)
        {
            var user = Session["LoginUser"] as User_Info;

            List<ExtendHouse_Source> DisList = new List<ExtendHouse_Source>();  //创建一个List
            StringBuilder sql = new StringBuilder();//实例化拼接对象

            var wheresql = "";
            if (user != null)
            {
                wheresql = "  Use_Id ='" + user.Use_Id + "'";
            }
            else
            {
                wheresql = " Use_Id = ''";
            }
            sql.AppendLine(string.Format(@"select a.*,Usecoll=(case when b.Use_Id is null then '0' else '1' end) from House_Source a 
left join (select * from Collect where {0} ) b on a.House_Id=b.House_Id where a.House_State<>2 or a.House_State<>3", wheresql));

            DisList = db.Database.SqlQuery<ExtendHouse_Source>(sql.ToString()).ToList();
            var retList = HouseList(DisList, htype, cityname, price, mjadd, zxadd);
            return JsonConvert.SerializeObject(retList);
        }
        /// <summary>
        ///   伙办办公/伙办公寓/伙办商铺 的列表和筛选
        /// </summary>
        /// <param name="htype">伙办办公/伙办公寓/伙办商铺 (房源类型)</param>
        /// <param name="cityname">所在城市</param>
        /// <param name="price">价格区间</param>
        /// <param name="mjadd">面积区间</param>
        /// <param name="zxadd">装修情况</param>
        /// <returns>Json</returns>
        public List<ExtendHouse_Source> HouseList(List<ExtendHouse_Source> WorkList, string htype, string cityname, string price, string mjadd, string zxadd)
        {
            if (htype == "伙办办公")
            {
                WorkList = WorkList.Where(a => a.House_Type == "伙办办公" && a.House_State == 1).ToList();
            }
            if (htype == "伙办公寓")
            {
                WorkList = WorkList.Where(a => a.House_Type == "伙办公寓" && a.House_State == 1).ToList();
            }
            if (htype == "伙办商铺")
            {
                WorkList = WorkList.Where(a => a.House_Type == "伙办商铺" && a.House_State == 1).ToList();
            }

            if (cityname != null)
            {
                WorkList = WorkList.Where(a => a.House_Address.Contains(cityname)).ToList();
            }
            if (price != null)
            {
                if (price == "1以下")
                {
                    WorkList = WorkList.Where(a => a.House_Price <= 1).ToList();
                }
                if (price == "1-3")
                {
                    WorkList = WorkList.Where(a => a.House_Price > 1 && a.House_Price <= 3).ToList();
                }
                if (price == "3-5")
                {
                    WorkList = WorkList.Where(a => a.House_Price > 3 && a.House_Price <= 5).ToList();
                }
                if (price == "5-10")
                {
                    WorkList = WorkList.Where(a => a.House_Price > 5 && a.House_Price <= 10).ToList();
                }
                if (price == "10以上")
                {
                    WorkList = WorkList.Where(a => a.House_Price > 10).ToList();
                }
            }
            if (mjadd != null)
            {
                if (mjadd.Contains("<100m"))
                {
                    WorkList = WorkList.Where(a => a.House_Area < 100).ToList();
                }
                if (mjadd.Contains("100-200"))
                {
                    WorkList = WorkList.Where(a => a.House_Area >= 100 && a.House_Area <= 200).ToList();
                }
                if (mjadd.Contains("200-300"))
                {
                    WorkList = WorkList.Where(a => a.House_Area > 200 && a.House_Area <= 300).ToList();
                }
                if (mjadd.Contains("300-500"))
                {
                    WorkList = WorkList.Where(a => a.House_Area > 300 && a.House_Area <= 500).ToList();
                }
                if (mjadd.Contains("500-1000"))
                {
                    WorkList = WorkList.Where(a => a.House_Area > 500 && a.House_Area <= 1000).ToList();
                }
                if (mjadd.Contains(">1000"))
                {
                    WorkList = WorkList.Where(a => a.House_Area > 1000).ToList();
                }
            }
            if (zxadd != null)
            {
                WorkList = WorkList.Where(a => a.House_Decorate.Contains(zxadd)).ToList();
            }
            return WorkList;
        }

        /// <summary>
        ///  房源收藏
        /// </summary>
        /// <param name="id">房源编号</param>
        /// <returns>受影响行数</returns>
        public int HouseCollect(int id)
        {
            var user = Session["LoginUser"] as User_Info;
            var collMode = db.Collect.Where(a => a.House_Id == id && a.Use_Id == user.Use_Id).FirstOrDefault();
            if (collMode != null) // 不为空就是已经收藏，要取消收藏
            {
                db.Collect.Remove(collMode);
                db.SaveChanges();  // 保存上下文
                return 2; // 取消收藏成功
            }
            else  // 否则进行收藏
            {
                Collect c = new Collect();
                c.Use_Id = user.Use_Id;
                c.House_Id = id;
                db.Collect.Add(c);
                return db.SaveChanges();  //返回受影响的行数1,收藏成功
            }
        }
        /// <summary>
        ///  地图找房
        /// </summary>
        /// <returns></returns>
        public ActionResult map()
        {
            var Province = db.City.Where(a => a.Pid == 0).ToList();
            return View();
        }
        /// <summary>
        /// 地图找房  -- 获取数据库内的全部房源 
        /// </summary>
        /// <returns></returns>
        public string HouseMessage_Map()
        {
            var list = db.House_Source.Where(a => a.House_State != 2 && a.House_State != 3).ToList();
            return JsonConvert.SerializeObject(list);
        }
        /// <summary>
        /// 地图找房，搜索房源
        /// </summary>
        /// <param name="House_Type"></param>
        /// <returns></returns>
        public string Map_HouseSearch(string House_Type, string cityname, string zxadd)
        {
            List<House_Source> list = new List<House_Source>();
            var arr = db.House_Source.Where(a => a.House_State != 2 && a.House_State != 3).ToList();
            if (House_Type != Convert.ToString(0))
            {
                list = arr.Where(n => n.House_Type == House_Type).ToList();
            }
            if (cityname != Convert.ToString(0))
            {
                list = arr.Where(n => n.House_Address.Contains(cityname)).ToList();
            }
            if (zxadd != Convert.ToString(0))
            {
                list = arr.Where(n => n.House_Decorate == zxadd).ToList();
            }
            return JsonConvert.SerializeObject(list);
        }
        /// <summary>
        ///  办公服务
        /// </summary>
        /// <returns></returns>
        public ActionResult officeService()
        {
            return View();
        }

        /// <summary>
        ///  个人中心
        /// </summary>
        /// <returns></returns>
        public ActionResult MyCenter()
        {
            var user = Session["LoginUser"] as User_Info;
            return View();
        }
        #endregion

        #region 绑定左侧导航栏
        /// <summary>
        ///  绑定父元素
        /// </summary>
        /// <returns></returns>
        public string LeftNav()
        {
            var user = Session["LoginUser"] as User_Info;
            var list = db.User_LimitAndRoles.Where(a => a.Roles_Id == user.Use_Role).ToList();
            return JsonConvert.SerializeObject(list);
        }
        /// <summary>
        ///  绑定子节点
        /// </summary>
        /// <param name="pid"></param>
        /// <returns></returns>
        public string LeftSon(int pid)
        {
            var list = db.User_Limit.Where(a => a.Limit_ParentId == pid).ToList();
            return JsonConvert.SerializeObject(list);
        }
        #endregion

        #region 绑定省市区
        /// <summary>
        ///  绑定省
        /// </summary>
        /// <returns></returns>
        public string BindProvince()
        {
            var Province = db.City.Where(a => a.Pid == 0).ToList();
            return JsonConvert.SerializeObject(Province);
        }
        /// <summary>
        ///  绑定市
        /// </summary>
        /// <param name="ProId"></param>
        /// <returns></returns>
        public string BindCity(string Proname)
        {
            if (Proname == "")
            {
                return "";
            }
            else
            {
                var proId = db.City.Where(s => s.C_Name == Proname).FirstOrDefault().C_Id;
                var City = db.City.Where(a => a.Pid == proId).ToList();
                return JsonConvert.SerializeObject(City);
            }
        }
        /// <summary>
        ///  绑定区域
        /// </summary>
        /// <param name="CityId"></param>
        /// <returns></returns>
        public string BindArea(string Cityname)
        {
            if (Cityname == "")
            {
                return "";
            }
            else
            {
                var CityId = db.City.Where(s => s.C_Name == Cityname).FirstOrDefault().C_Id;
                var Area = db.City.Where(a => a.Pid == CityId).ToList();
                return JsonConvert.SerializeObject(Area);
            }
        }
        #endregion

        #region 发布房源 委托找房
        /// <summary>
        /// 发布房源
        /// </summary>
        /// <param name="House_Name"></param>
        /// <param name="House_Intro"></param>
        /// <param name="House_Type"></param>
        /// <param name="House_Area"></param>
        /// <param name="House_Price"></param>
        /// <param name="House_FreeLease"></param>
        /// <param name="House_EarlyRentDate"></param>
        /// <param name="House_ShortRentDate"></param>
        /// <param name="House_FloorCount"></param>
        /// <param name="House_FloorHigh"></param>
        /// <param name="House_Decorate"></param>
        /// <param name="House_Person"></param>
        /// <param name="House_Telphone"></param>
        /// <param name="Province"></param>
        /// <param name="City"></param>
        /// <param name="Area"></param>
        /// <param name="House_Address"></param>
        /// <returns></returns>
        public ActionResult SendHouse(string House_Name, string House_Intro, string House_Type, int House_Area, double House_Price, int House_FreeLease, DateTime House_EarlyRentDate, int House_ShortRentDate, int House_FloorCount, double House_FloorHigh, string House_Decorate, string House_Person, string House_Telphone, string Province, string City, string Area, string House_Address)
        {

            var LoginName = Session["LoginUser"] as User_Info;
            House_Source hs = new House_Source();
            hs.House_Name = House_Name;
            hs.House_Intro = House_Intro;
            hs.House_Type = House_Type;
            hs.House_Area = House_Area;
            hs.House_Price = House_Price;
            hs.House_FreeLease = House_FreeLease;
            hs.House_ShortRentDate = House_ShortRentDate;
            hs.House_EarlyRentDate = House_EarlyRentDate;
            hs.House_FloorCount = House_FloorCount;
            hs.House_FloorHigh = House_FloorHigh;
            hs.House_Decorate = House_Decorate;
            hs.House_Person = House_Person;
            hs.House_Telphone = House_Telphone;
            hs.House_Address = Province + City + Area + House_Address;
            hs.House_CreatePeople = LoginName.Use_Id;
            hs.House_CreateTime = DateTime.Now;
            hs.House_State = 0;
            db.House_Source.Add(hs);
            var a = db.SaveChanges();
            House_Message m = new House_Message();
            m.Use_Id = LoginName.Use_Id;
            m.M_Title = "您的房源发布成功!";
            m.M_Content = "" + House_Telphone + "您好，您在" + DateTime.Now.ToShortDateString() + "发布的" + House_Name + "房源信息发布成功。 稍后客服将会联系您，与您进行房源详细信息的录入。 ";
            m.M_Time = DateTime.Now;
            m.IsDel = 0;
            db.House_Message.Add(m);
            var i = db.SaveChanges();
            if (i > 0)
            {
                return Content("<script>alert('房源发布成功了呢！请等待审核~');location.href='/Partner/MyCenter';</script>");
            }
            else
            {
                return Content("<script>alert('发布失败！麻烦您重新填写信息噢~');</script>");
            }
        }

        /// <summary>
        /// 短信验证接口
        /// </summary>
        /// <param name="mobiles"></param>
        /// <returns></returns>
        public static string PostUrl = ConfigurationManager.AppSettings["WebReference.Service.PostUrl"];
        /// 
        public string yzm(string mobiles)
        {
            if (mobiles != null)
            {
                string account = "C05025419";//是‘互亿无线’登陆后给的连接账号
                string password = "2da9b4f64c71e7e0d5ac151faa3c08db"; //请登录用户中心->验证码、通知短信->帐户及签名设置->APIKEY   这个key是我的，可以自己申请一个
                string mobile = mobiles;
                Random rad = new Random();//生成随机数
                int mobile_code = rad.Next(1000, 10000);
                string content = "您的验证码是：" + mobile_code + " 。请不要把验证码泄露给其他人。";//要发送的内容
                //Session["mobile"] = mobile;
                string postStrTpl = "account={0}&password={1}&mobile={2}&content={3}&format={4}";//拼接字符串形成请求体
                using (HttpClient client = new HttpClient())//用客户端请求API数据
                {
                    //进行utf-8进行编码解析；因为API接口需要密文以字节数组的形式发送
                    UTF8Encoding encoding = new UTF8Encoding();
                    //将请求体编码成字节数组
                    byte[] postData = encoding.GetBytes(string.Format(postStrTpl, account, password, mobile, content, "json"));
                    //设置请求体
                    HttpContent contents = new ByteArrayContent(postData, 0, postData.Length);
                    //设置请求头（包头）成字节数组
                    contents.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/x-www-form-urlencoded");
                    //请求结果
                    var result = client.PostAsync(PostUrl, contents).Result;
                    //判断请求结果的状态码
                    if (result.IsSuccessStatusCode)
                    {
                        //返回的json结果
                        var jj = result.Content.ReadAsStringAsync().Result;
                        Session["PhoneYzm"] = mobile_code;//可以那此值与客户输入的验证码作比较。
                        //已发送的验证码
                        return jj;
                    }
                    else
                    {
                        var jj = result.StatusCode;
                        return Newtonsoft.Json.JsonConvert.SerializeObject("code:1");
                    }
                }
            }
            return Newtonsoft.Json.JsonConvert.SerializeObject("code:1");
        }
        /// <summary>
        /// 找回密码    
        /// </summary>
        /// <param name="Phone"></param>
        /// <param name="Yzm"></param>
        /// <returns></returns>
        public string GetYzm(string Phone, string Yzm)
        {
            var list = db.User_Info.ToList();
            var PhoneYzm = Session["PhoneYzm"].ToString();
            var userlist = list.Where(n => n.Use_Telphone == Phone).FirstOrDefault();
            if (userlist == null)
            {
                return "101";
            }
            if (Yzm == PhoneYzm)
            {
                var arr = list.Where(n => n.Use_Telphone == Phone).FirstOrDefault();
                return JsonConvert.SerializeObject(arr);
            }
            else
            {
                return null;
            }
        }
        /// <summary>
        /// 委托找房
        /// </summary>
        /// <param name="E_Type"></param>
        /// <param name="E_Decorate"></param>
        /// <param name="E_Area"></param>
        /// <param name="Province"></param>
        /// <param name="City"></param>
        /// <param name="Area"></param>
        /// <param name="E_Price"></param>
        /// <param name="E_HopeSell"></param>
        /// <param name="E_Telphone"></param>
        /// <param name="E_Remark"></param>
        /// <returns></returns>
        public ActionResult FindHouse(string E_Type, string E_Decorate, string E_Area, string Province2, string City, string Area, string E_Price, string E_HopeSell, string E_Telphone, string E_Remark)
        {
            var LoginName = Session["LoginUser"] as User_Info;
            House_Entrust he = new House_Entrust();
            he.E_Type = E_Type;
            he.E_Decorate = E_Decorate;
            he.E_Area = E_Area;
            he.E_Address = Province2 + City + Area;
            he.E_Price = E_Price;
            he.E_HopeSell = E_HopeSell.ToString();
            he.E_Telphone = E_Telphone;
            he.E_Remark = E_Remark;
            he.E_CreatePeople = LoginName.Use_Id;
            he.E_CreateTime = DateTime.Now;
            he.E_State = 0;
            db.House_Entrust.Add(he);
            var a = db.SaveChanges();

            House_Message m = new House_Message();
            m.Use_Id = LoginName.Use_Id;
            m.M_Title = "您的委托发布成功!";
            m.M_Content = "" + E_Telphone + "您好，您在" + DateTime.Now.ToShortDateString() + "发布的委托我们已收到。客服将会尽快为您找到满意的房源，请耐心等待。 ";
            m.M_Time = DateTime.Now;
            m.IsDel = 0;
            db.House_Message.Add(m);
            var i = db.SaveChanges();
            if (i > 0)
            {
                return Content("<script>alert('委托房源成功啦！请耐心等待噢~');location.href='/Partner/MyCenter';</script>");
            }
            else
            {
                return Content("<script>alert('委托失败了QAQ！麻烦您重新填写信息噢~');</script>");
            }
        }
        #endregion

    }
}
